package com.zhehekeji.opsys.api.service.validate;

import java.util.Date;

import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zhehekeji.opsys.api.code.LuckyDrawResultCode;
import com.zhehekeji.opsys.api.common.util.SuperResp;
import com.zhehekeji.opsys.api.entity.TActivity;
import com.zhehekeji.opsys.api.service.validate.args.ActivityValidateArgs;

/**
 * @ClassName ActivityValidate
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-4-10   下午4:54:09
 */
@Service
public class ActivityValidate extends ValidateService<ValidateRets<TActivity>, ActivityValidateArgs>{
	
	private final static Logger logger = LoggerFactory.getLogger(ActivityValidate.class);
	
	@Override
	public ValidateRets<TActivity> validate(ActivityValidateArgs validateArgs)
			throws Exception {
		ValidateRets<TActivity> validateRets = new ValidateRets<TActivity>();
		SuperResp resp = validateArgs.getResp();
		String activityCode = validateArgs.getActivityCode();
		Date currentDate = validateArgs.getCurrentDate();
		if (StringUtils.isEmpty(activityCode)){
			logger.error("活动编码["+activityCode+"]非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("活动编码非法！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		TActivity tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
		if (tmpTActivity == null){
			logger.error("活动编码["+activityCode+"]非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("活动编码非法！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		Integer tmpStatus = tmpTActivity.getStatus();
		if (tmpStatus == 0){
			logger.error("活动["+activityCode+"]已经停用！status="+tmpStatus);
			resp.setResultCode(LuckyDrawResultCode.ACTIVITY_HAS_BEEN_STOPPED);
			resp.setResultDesc("活动已经停用！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		Date tmpStartTime = tmpTActivity.getStartTime();
		Date tmpEndTime = tmpTActivity.getEndTime();
		if (tmpStartTime == null || tmpEndTime == null){
			logger.error("活动["+activityCode+"]没有开始时间，结束时间！");
			resp.setResultCode(LuckyDrawResultCode.DATABASE_EXCEPTION);
			resp.setResultDesc("数据异常！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		if (currentDate.compareTo(tmpStartTime) <0){
			logger.error("活动["+activityCode+"]还未开始！");
			resp.setResultCode(LuckyDrawResultCode.ACTIVITY_HAS_YET_TO_BEGIN);
			resp.setResultDesc("活动还未开始！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		if (currentDate.compareTo(tmpEndTime) >0){
			logger.error("活动["+activityCode+"]已经结束！");
			resp.setResultCode(LuckyDrawResultCode.ACTIVITY_HAS_COME_TO_AN_END);
			resp.setResultDesc("活动已经结束！");
			validateRets.setSuccess(false);
			return validateRets;
		}
		validateRets.setEntity(tmpTActivity);
		return validateRets;
	}
}
